package cn.gzsf.weibo.controller;


import cn.gzsf.weibo.mapper.CommentMapper;
import cn.gzsf.weibo.mapper.WeiboMapper;
import cn.gzsf.weibo.pojo.dto.WeiboDTO;
import cn.gzsf.weibo.pojo.entity.User;
import cn.gzsf.weibo.pojo.entity.Weibo;
import cn.gzsf.weibo.pojo.vo.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/weibo/")
public class WeiboController {

    @Autowired
    private WeiboMapper weiboMapper;

    @RequestMapping("insert")
    public int insert(@RequestBody WeiboDTO weiboDTO, HttpSession session){
        System.out.println("weiboDTO="+weiboDTO);
        UserVO  user= (UserVO)session.getAttribute("user");
        if(user==null){
            return 2;//未登录
        }
        //往数据库存数据时用entity
        Weibo weibo = new Weibo();
        //将weiboDTO的属性复制给weibo对象
        BeanUtils.copyProperties(weiboDTO,weibo);
        //给weibo对象的其他属性赋值
        weibo.setUserId(user.getId());//设置当前登录的用户id为微博作者的id
        weibo.setCreated(new Date());//设置当前时间为发布微博时间
        System.out.println("weibo="+weibo);

        weiboMapper.insert(weibo);

        return 1;
     }

    @RequestMapping("select")
    public List<WeiboIndexVO> select(){
        return weiboMapper.select();
     }

    @RequestMapping("selectById")
    public WeiboDetailVO selectById(int id){
        return weiboMapper.selectById(id);
    }

    @RequestMapping("select/mine")
    public ResultVO selectWeiboMine(HttpSession session){
        UserVO  user= (UserVO)session.getAttribute("user");
        if(user==null){//未登录
            return  new ResultVO(2,"用户未登录",null);
        }
        //如果没有发布微博响应的是一个空集合，客户端收到之后也会解析为空字符串
        return new ResultVO(1,"请求成功",weiboMapper.selectMine(user.getId()));
    }


    @Autowired
    private CommentMapper commentMapper;
    @RequestMapping("delete")
    public void delete(int id){//weibo的Id
        //删除相关评论
        commentMapper.deleteByWeiboId(id);
        //删除微博
        weiboMapper.deleteById(id);
    }
}
